package com.agency8x.controller;

import com.agency8x.bean.JsonResultBean;
import com.agency8x.config.AppConf;
import com.agency8x.interceptor.CheckLoginInterceptor;
import com.agency8x.model.AdminModel;
import com.agency8x.model.LoginModel;
import com.agency8x.util.DateTimeUtil;
import com.agency8x.validator.AdminValidator;
import com.agency8x.web.util.ControllerUtil;
import com.agency8x.web.util.PoiExcelExporter;
import com.agency8x.web.util.ResponseUtil;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.Render;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 管理员页控制器
 *
 * @author SoChishun
 *
 */
@Before(CheckLoginInterceptor.class)
public class AdminController extends Controller {

    public void index() {
        String search_word = this.getPara("word");// 搜索
        setAttr("listPage", AdminModel.me.paginate(getParaToInt(0, 1), 10, search_word));
        // 设置传入分页的url参数
        if (StrKit.notBlank(search_word)) {
            this.setAttr("append", "?word=" + search_word);
        }
        this.render("index.html");
    }

    public void edit() {
        Integer user_id = this.getParaToInt();
        if (null != user_id && user_id > 0) {
            AdminModel model = AdminModel.me.findById(user_id);
            this.setAttr("itemData", model);
        }
        this.render("edit.html");
    }
    public void doExport2(){
    	List<Record> list = AdminModel.me.getRecords();
    	Render poirender = new Render() {
            @Override
            public void render() {
                String date=DateTimeUtil.formatDateTime(new Date(), "Ymd");
                String fileName="Admin"+date+".xls";
                ResponseUtil.setPoiDowloadHeader(response, fileName);
                PoiExcelExporter exporter = new PoiExcelExporter(list, fileName, "管理员-"+date);
                HashMap<String,String> headerMap=new HashMap<String,String>();
                headerMap.put("用户编号", "user_id");
                headerMap.put("用户名", "user_name");
                headerMap.put("手机号码", "mobile");
                headerMap.put("电子邮件", "email");
                try {
                    exporter.export(headerMap,response.getOutputStream());
                } catch (IOException ex) {
                    Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        this.render(poirender);
    	
    }

    public void doExport() {
        List<Record> list = AdminModel.me.getRecords();
        Render poirender = new Render() {
            @Override
            public void render() {
                String date=DateTimeUtil.formatDateTime(new Date(), "Ymd");
                String fileName="Admin"+date+".xls";
                ResponseUtil.setPoiDowloadHeader(response, fileName);
                PoiExcelExporter exporter = new PoiExcelExporter(list, fileName, "管理员-"+date);
                try {
                    exporter.export(response.getOutputStream());
                } catch (IOException ex) {
                    Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        this.render(poirender);
    }

    @Before(AdminValidator.class)
    public void doSave() {
        Integer user_id = this.getParaToInt("user_id");
       AdminModel model = getModel(AdminModel.class, "");
       model.removeNullValueAttrs();
        boolean result = false;
        if (null == user_id) {
            result = model.save();
        } else {
            result = model.update();
        }
        if (result) {
            LoginModel.me.updateFaceUrl(this, AppConf.loginSessionID, this.getPara("face_url", ""));
            ControllerUtil.renderDisptchJumpSuccess(this); // 操作成功，倒计时3秒后自动刷新列表页面
        } else {
            ControllerUtil.renderDisptchJumpError(this, "保存失败"); // 操作失败，倒计时3秒后，自动后退到提交的表单页面
        }
    }

    public void profile() {
        LoginModel loginBean = LoginModel.getLoginInfo(this, AppConf.loginSessionID);
        if (null == loginBean) {
            this.renderText("登录超时或未登录");
            return;
        }
        AdminModel model = AdminModel.me.findById(loginBean.getUserId());
        if (null == model) {
            this.renderText("记录不存在");
            return;
        }
        this.setAttr("itemData", model);
        this.render("profile.html");
    }

    public void doSaveProfile() {
        boolean result = getModel(AdminModel.class, "").update();
        if (result) {
            ControllerUtil.renderDisptchJumpSuccess(this); // 操作成功，倒计时3秒后自动刷新列表页面
        } else {
            ControllerUtil.renderDisptchJumpError(this, "保存失败"); // 操作失败，倒计时3秒后，自动后退到提交的表单页面
        }
    }

    /**
     * 删除操作 <br />
     * 支持单个删除和批量删除 <br />
     * 单个删除：?id=1 <br />
     * 批量删除：?id=1,2,3
     *
     * @since 1.0 2017-5-15
     */
    public void doDelete() {
        boolean result = false;
        String user_id = this.getPara("user_id");
        if (null != user_id) {
            result = AdminModel.me.deleteById(user_id);
        }
        this.renderJson(new JsonResultBean(result, "删除" + (result ? "成功" : "失败")));
    }

    private void setFileName(String path) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
